//
//  YXNetWorkCache.m
//  iOS_YouSelect
//
//  Created by cyMac on 2018/7/9.
//  Copyright © 2018年 cong. All rights reserved.
//

#import "YXNetWorkCache.h"
#import "YYCache/YYCache.h"
static NSString *const kYXNetworkResponseCache = @"kYXNetworkResponseCache";
@implementation YXNetWorkCache
static YYCache *_dataCache;

+ (void)initialize {
    _dataCache = [YYCache cacheWithName:kYXNetworkResponseCache];
}

+ (void)setHttpCache:(id)httpData URL:(NSString *)URL parameters:(NSDictionary *)parameters {
    NSString *cacheKey = [self cacheKeyWithURL:URL parameters:parameters];
    [_dataCache setObject:httpData forKey:cacheKey withBlock:nil];
}

+ (id)httpCacheForURL:(NSString *)URL parameters:(NSDictionary *)parameters {
    NSString *cacheKey = [self cacheKeyWithURL:URL parameters:parameters];
    return [_dataCache objectForKey:cacheKey];
}

+ (NSInteger)getAllHttpCacheSize {
    return [_dataCache.diskCache totalCost];
}

+ (void)removeCacheWithURL:(NSString *)URL parameters:(NSDictionary *)parameters {
    NSString *cacheKey = [self cacheKeyWithURL:URL parameters:parameters];
    [_dataCache removeObjectForKey:cacheKey withBlock:^(NSString * _Nonnull key) {
//        YXLog(@"清空缓存:removeObjectForKey%@----%@",key,[NSThread currentThread]);
    }];
}

+ (void)removeCacheWithURL:(NSString *)URL parameters:(NSDictionary *)parameters finishBlock:(void (^)(NSString *key))block{
    NSString *cacheKey = [self cacheKeyWithURL:URL parameters:parameters];
    [_dataCache removeObjectForKey:cacheKey withBlock:^(NSString * _Nonnull key) {
//        YXLog(@"清空缓存:removeObjectForKey%@----%@",key,[NSThread currentThread]);
        if (block) {
            block(key);
        }
    }];
}

+ (void)removeAllHttpCache
{
    [_dataCache.diskCache removeAllObjects];
}

+ (NSString *)cacheKeyWithURL:(NSString *)URL parameters:(NSDictionary *)parameters {
    if(!parameters || parameters.count == 0){return URL;};
    //参数字典转str
    NSData *stringData = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:nil];
    NSString *paraString = [[NSString alloc] initWithData:stringData encoding:NSUTF8StringEncoding];
    return [NSString stringWithFormat:@"%@%@",URL,paraString];
}



@end
